package edu.biwu.response;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/resp/download01")
public class RespDownload01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         //1.获取浏览器传递的fileName参数,该参数可以指定下载哪个文件
        String fileName = request.getParameter("fileName");
        System.out.println(fileName);

        //2.设置响应头
        //需要设置MIME类型,还需要设置一个附件相关的头
        String mimeType = getServletContext().getMimeType(fileName);
        response.setHeader("Content-Type", mimeType);
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);//这个头告诉浏览器相应的文件是一个附件,浏览器会弹窗下载,并显示文件名

        //3.响应文件内容,利用字节流读取服务器文件,写给浏览器
        InputStream is = getServletContext().getResourceAsStream("/download/" + fileName);
        BufferedInputStream bis = new BufferedInputStream(is);

        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());

        int b;
        while ((b = bis.read()) != -1) {
            //最终写给浏览器
            bos.write(b);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
